//
//  CZRotateView.m
//  01-幸运大转盘
//
//  Created by apple on 15/10/31.
//  Copyright (c) 2015年 1. All rights reserved.
//

#import "CZRotateView.h"
#import <SVProgressHUD.h>



@interface CZRotateView () <UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UIImageView* rotateWheel; // 锯齿图片

@property (strong, nonatomic) CADisplayLink* link;

@property (weak, nonatomic) UIButton* currentButton;

@end

@implementation CZRotateView

+ (instancetype)rotateView
{
    return [[NSBundle mainBundle] loadNibNamed:@"CZRotateView" owner:nil options:nil][0];
}

- (void)awakeFromNib
{
    // 创建12个按钮
    for (int i = 0; i < 12; i++) {
        UIButton* btn = [[UIButton alloc] init];
        btn.layer.anchorPoint = CGPointMake(0.5, 1);
        [self.rotateWheel addSubview:btn];

        // 监听选中按钮
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
}
// 开始选号的点击事件
- (IBAction)pickNumber:(id)sender
{

    if (!self.currentButton) {
        [SVProgressHUD showWithStatus:@"请选择一个星座" maskType:SVProgressHUDMaskTypeBlack];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }

    if (![self.rotateWheel.layer animationForKey:@"key"]) {

        self.link.paused = YES;

        // 创建一个基本动画
        CABasicAnimation* anim = [[CABasicAnimation alloc] init];

        // 操作
        anim.keyPath = @"transform.rotation";
        CGFloat angle = self.currentButton.tag * 2 * M_PI / 12; // 选中按钮应该少转的角度
        anim.toValue = @(2 * M_PI * 2  - angle);

        anim.duration = 3;

        // 不回到原来的位置
        anim.fillMode = kCAFillModeForwards;
        anim.removedOnCompletion = NO;

        // 添加
        [self.rotateWheel.layer addAnimation:anim forKey:@"key"];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(anim.duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 修改一下锯齿图片的transform
            self.rotateWheel.transform = CGAffineTransformMakeRotation([anim.toValue floatValue]);

            // alertView
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"你的幸运号码是xxxx" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];

            // 移除核心动画
            [self.rotateWheel.layer removeAnimationForKey:@"key"];

        });
    }
}

// 点击alertView的方法
- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    self.link.paused = NO;
}

// 开始旋转
- (void)startRotate
{
    CADisplayLink* link = [CADisplayLink displayLinkWithTarget:self selector:@selector(rotate)];
    // 把link添加到运行循环里面去
    [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

    self.link = link;
}

// 旋转
- (void)rotate
{

    // 计算角度
    // 2 * mpi   1秒  60圈
    // 2 * mpi / 60 1秒 1圈
    // 2 * mpi / 60 / 10 10秒 1圈

    CGFloat angle = 2 * M_PI / 60 / 5;
    self.rotateWheel.transform = CGAffineTransformRotate(self.rotateWheel.transform, angle);
}

// 十二个按钮的点击事件
- (void)btnClick:(UIButton*)sender
{
    self.currentButton.selected = NO; // 取消上一次按钮的选中状态
    sender.selected = YES; // 设置当前点击的按钮为选中状态
    self.currentButton = sender; // 记录一下刚才选中的按钮
}

- (void)layoutSubviews
{

    //
    [super layoutSubviews];

    // 设置按钮的frame

    for (int i = 0; i < self.rotateWheel.subviews.count; i++) {
        // 获取按钮
        UIButton* btn = self.rotateWheel.subviews[i];
        btn.tag = i; // 计算开始选号应该旋转到的角度
        CGFloat w = 68;
        CGFloat h = 143;
        CGFloat x = 0;
        CGFloat y = 0;

        // 设置frame
        btn.frame = CGRectMake(x, y, w, h);

        // 设置中心点
        btn.center = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);

        // 散开
        // 一个按钮应该旋转的角度
        CGFloat angle = 2 * M_PI / 12;
        btn.transform = CGAffineTransformMakeRotation(angle * i);

        // 获取原图
        UIImage* astrology = [UIImage imageNamed:@"LuckyAstrology"];
        // 获取裁剪过后的图片
        astrology = [self clipImageWithImage:astrology andIndex:i];
        // 设置图片
        [btn setImage:astrology forState:UIControlStateNormal];

        // 设置按钮的背景图片
        [btn setBackgroundImage:[UIImage imageNamed:@"LuckyRototeSelected"] forState:UIControlStateSelected];

        // 获取原图
        UIImage* astrologyPress = [UIImage imageNamed:@"LuckyAstrologyPressed"];
        // 获取裁剪过后的图片
        astrologyPress = [self clipImageWithImage:astrologyPress andIndex:i];
        // 设置图片
        [btn setImage:astrologyPress forState:UIControlStateSelected];

        // btn内部的图片的位置 偏上一些
        [btn setImageEdgeInsets:UIEdgeInsetsMake(-50, 0, 0, 0)];
    }
}

// 裁剪图片
- (UIImage*)clipImageWithImage:(UIImage*)image andIndex:(int)index
{
    CGFloat w = image.size.width / 12 * [UIScreen mainScreen].scale;
    CGFloat h = image.size.height * [UIScreen mainScreen].scale;
    CGFloat x = index * w;
    CGFloat y = 0;
    // 根据某一区域去裁剪某张图片(获取图片的一部分)
    CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, CGRectMake(x, y, w, h));
    // 把imageRef转成UIimage
    return [UIImage imageWithCGImage:imageRef scale:2.4 orientation:UIImageOrientationUp];
}
@end
